package oktx.sample.dubbo;

import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import oktx.sample.dubbo.model.Book;
import oktx.sample.dubbo.model.Shop;
import oktx.sample.dubbo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by dave on 18-5-20 上午11:46.
 */
@Api(description = "用户接口")
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired UserMapper userMapper;
    @Reference(loadbalance = "roundrobin") ShopApi shopApi;

    @Transactional
    @ApiOperation("一个老板开书店并进货图书的故事")
    @GetMapping("/makeupStory")
    public Book makeupStory(@ApiParam("事务类型") @RequestParam("type") PostType type) {
        // 录入老板信息
        User u = new User();
        u.setName("老板");
        u.setPhone("13312345678");
        userMapper.insert(u);

        // 创建书店
        Shop s = new Shop();
        s.setName("新星书店");
        s.setAddress("武汉光谷广场");
        s = shopApi.addShop(s);

        // 书店进货
        Book b = new Book();
        b.setName("创业圣经");
        b.setNum(10);
        b.setContent("这里是图书内容");
        b.setShopId(s.getId());
        b = shopApi.restock(b, type);

        if (type == PostType.commit) {
            return b;
        } else {
            throw new RuntimeException("已取消写入数据库");
        }
    }
}
